#include<stdio.h>  
#include<stdlib.h>  
#include<string.h>  
#include<errno.h>  
#include<sys/types.h>  
#include<sys/socket.h>  
#include<netinet/in.h>
#include <pthread.h>
#include<arpa/inet.h>
#include <fcntl.h> // for open
#include <unistd.h> // for close
#include "tcp.h"
#include <wiringPi.h>

#define MAXLINE 4096
int    sockfd;
struct sockaddr_in    servaddr;

pthread_t thread_recv;
struct ledControl leds={0,0,0,1,0,0};

int ConnectToSvr(char *ip,int port)
{	
	if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){  
    printf("create socket error: %s(errno: %d)\n", strerror(errno),errno);  
    exit(0);  
    }  
	memset(&servaddr, 0, sizeof(servaddr));  
    servaddr.sin_family = AF_INET;  
    servaddr.sin_port = htons(port);  
    if( inet_pton(AF_INET, ip, &servaddr.sin_addr) <= 0){  
    printf("inet_pton error for %s\n",ip);  
    exit(0);  
    }  
	if( connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0){  
    printf("connect error: %s(errno: %d)\n",strerror(errno),errno);  
    exit(0);  
    }
	// create a thread to recv data	
	pthread_create(&thread_recv,NULL, (void *)(&RecvData), NULL);
 
	return 0;
}
int SendData(char * sData)
{
	if( send(sockfd, sData, strlen(sData), 0) < 0)  
    {  
		printf("send msg error: %s(errno: %d)\n", strerror(errno), errno);  
    }  
	return 0;
}
void RecvData(void)
{
	int rec_len;
	char    buf[MAXLINE];
	for(;;)
	{
		if((rec_len = recv(sockfd, buf, MAXLINE,0)) == -1) {  
			perror("recv error\n");  
			exit(1);  
		}
		printf("Recv Data [%s]\n",buf);
		if(strncmp(buf,"G0",2)==0)
		{
			leds.manualControl=1;
			leds.refresh=1;
			leds.iGreenLedStat=0;			
		}else if(strncmp(buf,"G1",2)==0)
		{			
			leds.manualControl=1;
			leds.refresh=1;
			leds.iGreenLedStat=1;
		}else if(strncmp(buf,"B0",2)==0)
		{
			leds.manualControl=1;
			leds.iBlueLedStat=0;
			leds.refresh=1;

		}else if(strncmp(buf,"B1",2)==0)
		{
			leds.manualControl=1;
			leds.iBlueLedStat=1;
			leds.refresh=1;

		}else if(strncmp(buf,"EXIT",4)==0)
		{
			leds.manualControl=1;
			leds.exitFlag=1;
			leds.refresh=1;
			break;
		}else{
			printf("Unknow command!\n");
		}
	}
	printf("Recv Data Thread is exit!!!\n");
}
int DisconectSvr(void){
	close(sockfd);
	return 0;
}